"""认证模块视图"""
from rest_framework import generics, status, viewsets
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.response import Response
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
from django.contrib.auth.models import User
from drf_spectacular.utils import extend_schema, extend_schema_view
from apps.common.responses import (
    ApiResponseMixin,
    create_success_response_serializer,
    ValidationErrorResponseSerializer,
    UnauthorizedErrorResponseSerializer
)
from .serializers import (
    UserRegistrationSerializer,
    UserProfileSerializer,
    ChangePasswordSerializer,
    TokenResponseSerializer
)

@extend_schema_view(
    post=extend_schema(
        summary="用户注册",
        description="创建新用户账户",
        responses={
            201: create_success_response_serializer(UserProfileSerializer, "注册成功", "Register"),
            400: ValidationErrorResponseSerializer,
        }
    )
)
class RegisterView(ApiResponseMixin, generics.CreateAPIView):
    """用户注册视图"""
    queryset = User.objects.all()
    serializer_class = UserRegistrationSerializer
    permission_classes = [AllowAny]

    def create(self, request, *args, **kwargs):
        """创建用户"""
        serializer = self.get_serializer(data=request.data)
        if not serializer.is_valid():
            return self.error_response(
                message="注册信息验证失败",
                errors=serializer.errors,
                code=400
            )

        user = serializer.save()
        user_data = UserProfileSerializer(user).data

        return self.success_response(
            data=user_data,
            message="注册成功",
            code=201
        )

@extend_schema_view(
    retrieve=extend_schema(
        summary="获取当前用户信息",
        description="获取当前登录用户的详细信息",
        responses={
            200: create_success_response_serializer(UserProfileSerializer, "获取成功", "Retrieve"),
            401: UnauthorizedErrorResponseSerializer,
        }
    ),
    update=extend_schema(
        summary="更新用户信息",
        description="更新当前用户的基本信息",
        responses={
            200: create_success_response_serializer(UserProfileSerializer, "更新成功", "Update"),
            400: ValidationErrorResponseSerializer,
            401: UnauthorizedErrorResponseSerializer,
        }
    ),
    partial_update=extend_schema(
        summary="部分更新用户信息",
        description="部分更新当前用户的基本信息",
        responses={
            200: create_success_response_serializer(UserProfileSerializer, "更新成功", "PartialUpdate"),
            400: ValidationErrorResponseSerializer,
            401: UnauthorizedErrorResponseSerializer,
        }
    )
)
class UserProfileViewSet(ApiResponseMixin, viewsets.GenericViewSet):
    """用户信息ViewSet - 支持获取、更新当前用户信息和修改密码"""
    serializer_class = UserProfileSerializer
    permission_classes = [IsAuthenticated]
 
    def get_object(self):
        """获取当前用户"""
        return self.request.user

    def retrieve(self, request, *args, **kwargs):
        """获取用户信息"""
        user = self.get_object()
        serializer = self.get_serializer(user)
        return self.success_response(
            data=serializer.data,
            message="获取成功"
        )

    def update(self, request, *args, **kwargs):
        """更新用户信息"""
        partial = kwargs.pop('partial', False)
        user = self.get_object()
        serializer = self.get_serializer(user, data=request.data, partial=partial)

        if not serializer.is_valid():
            return self.error_response(
                message="信息验证失败",
                errors=serializer.errors,
                code=400
            )

        serializer.save()
        return self.success_response(
            data=serializer.data,
            message="更新成功"
        )

    def partial_update(self, request, *args, **kwargs):
        """部分更新用户信息"""
        kwargs['partial'] = True
        return self.update(request, *args, **kwargs)

    @extend_schema(
        summary="修改密码",
        description="修改当前用户的登录密码",
        request=ChangePasswordSerializer,
        responses={
            200: create_success_response_serializer(UserProfileSerializer, "密码修改成功", "ChangePassword"),
            400: ValidationErrorResponseSerializer,
            401: UnauthorizedErrorResponseSerializer,
        }
    )
    @action(detail=False, methods=['post'])
    def change_password(self, request):
        """修改密码"""
        serializer = ChangePasswordSerializer(data=request.data, context={'request': request})

        if not serializer.is_valid():
            return self.error_response(
                message="密码验证失败",
                errors=serializer.errors,
                code=400
            )

        # 更新密码
        user = request.user
        user.set_password(serializer.validated_data['new_password'])
        user.save()

        # 返回更新后的用户信息
        user_data = UserProfileSerializer(user).data
        return self.success_response(
            data=user_data,
            message="密码修改成功"
        )




# 🔑 关键：自定义JWT Token视图，确保返回统一响应格式
@extend_schema(
    summary="用户登录",
    description="用户登录获取JWT Token",
    responses={
        200: create_success_response_serializer(TokenResponseSerializer, "登录成功", "Login"),
        401: UnauthorizedErrorResponseSerializer,
        400: ValidationErrorResponseSerializer,
    }
)
class CustomTokenObtainPairView(TokenObtainPairView, ApiResponseMixin):
    """自定义JWT Token获取视图 - 返回统一响应格式"""

    def post(self, request, *args, **kwargs):
        response = super().post(request, *args, **kwargs)
        if response.status_code == 200:
            # 🔑 关键：确保返回的是Token数据，而不是用户信息
            token_data = response.data
            print(token_data,'---')
            return self.success_response(token_data, "登录成功")
        return self.error_response('认证失败', response.data, response.status_code)


@extend_schema(
    summary="刷新Token",
    description="使用refresh token获取新的access token",
    responses={
        200: create_success_response_serializer(TokenResponseSerializer, "Token刷新成功", "Refresh"),
        401: UnauthorizedErrorResponseSerializer,
        400: ValidationErrorResponseSerializer,
    }
)
class CustomTokenRefreshView(TokenRefreshView, ApiResponseMixin):
    """自定义JWT Token刷新视图 - 返回统一响应格式"""

    def post(self, request, *args, **kwargs):
        response = super().post(request, *args, **kwargs)
        if response.status_code == 200:
            return self.success_response(response.data, "Token刷新成功")
        return self.error_response('Token刷新失败', response.data, response.status_code)
